<?php

namespace addons\zzyy\controller\api;

use addons\zzyy\module\Weixin;
use addons\zzyy\library\Ykxbon;
use app\admin\model\user\Balance;
use app\admin\model\user\Extend;
use app\admin\model\zzyy\ZzyyReserve;
use app\admin\model\zzyy\ZzyyRoom;
use app\admin\model\zzyy\ZzyySetting;
use app\admin\model\zzyy\ZzyyStore;
use app\admin\model\zzyy\ZzyyThird;
use app\admin\model\zzyy\ZzyyTransaction;
use app\admin\model\zzyy\ZzyyUserBalance;
use app\admin\model\zzyy\ZzyyUserExtend;
use Carbon\Carbon;
use think\Db;

class User extends \app\common\controller\Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function getUserInfo()
    {
        $userId = $this->auth->getUser()->id;
        $userInfo = \addons\zzyy\module\User::getUserInfo($userId);
        $this->success('ok', $userInfo);
    }

    public function saveUserInfo()
    {
        if ($this->request->isPost()) {
            $userId = $this->auth->getUser()->id;
            $avatar = $this->request->post('avatar');
            $nickname = $this->request->post('nickname');
            $gender = $this->request->post('gender');
            $mobile = $this->request->post('mobile');
            $birthday = $this->request->post('birthday');

            $user = \app\admin\model\User::get($userId);

            $user->avatar = $avatar;
            $user->nickname = $nickname;
            $user->gender = $gender;
            $user->mobile = $mobile;
            $user->birthday = $birthday;
            $user->save();

            $this->getUserInfo();
        }
        $this->error('need post request');
    }

    public function mpWeixinDecodePhone()
    {
        $userId = $this->auth->getUser()->id;
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');

        $sessionkey = ZzyyThird::where('user_id', $userId)->find()->sessionkey;

        if (strlen($sessionkey) != 24) {
            $this->error('encodingAesKey 非法');
        }
        $aesKey = base64_decode($sessionkey);
        if (strlen($iv) != 24) {
            $this->error('iv 非法');
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);

        $decryptedData = openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $decryptedData = json_decode($decryptedData);

        if( $decryptedData  == NULL ) {
            $this->error('aes 解密失败');
        }
        $addonConfig = get_addon_config('zzyy');
        if( $decryptedData->watermark->appid != $addonConfig['mp_appid'] ) {
            $this->error('aes 解密失败');
        }

//        $decryptedData = Weixin::getInstance()->minProgram()->encryptor->decryptData($sessionkey, $iv, $encryptedData);

        $this->success('ok', ['phone' => $decryptedData->phoneNumber]);
    }

    public function getMyReserveList()
    {
        $user = $this->auth->getUser();
        if (null == $user) {
            $this->error('未登录');
        }
        $userId = $user->id;

        $reserves = ZzyyReserve::where('user_id', $userId)
            ->where('status', ZzyyReserve::STATUS_SUCCESS)
            ->where('endtime', '>', Ykxbon::now()->toDateTimeString())
            ->order('starttime', 'asc')
            ->select();

        $reserves = array_map(function ($e) {
            $id = $e->id;
            return \addons\zzyy\module\Reserve::getReserveFormatInfo($id);
        }, $reserves);

        $this->success('ok', $reserves);


    }

    public function getUserAllReservation()
    {
        $userId = $this->auth->getUser()->id;
        $reserves = ZzyyReserve::with(['store', 'room'])->where('user_id', $userId)->order('id', 'desc')->select();
        $reserves = array_map(function ($e) {
            return [
                'id' => $e->id,
                'store_name' => $e->store->store_name,
                'room_name' => $e->room->room_name,
                'price' => $e->fee,
                'pay_way' => $e->pay_way,
                'starttime' => $e->starttime,
                'endtime' => $e->endtime,
                'createtime' => $e->createtime,
                'order_num' => $e->trade_no,
                'status' => $e->status,
            ];
        }, $reserves);

        $this->success('ok', $reserves);
    }

    public function getBalanceInfo()
    {
        $userId = $this->auth->getUser()->id;
        $money = ZzyyUserExtend::where('user_id', $userId)->find()->balance;

        $stores = ZzyyStore::all();
        $storesMap  = [];
        foreach ($stores as $store) {
            $storesMap[$store->id] = $store->store_name;
        }

        $rooms = ZzyyRoom::all();
        $roomsMap = [];
        foreach ($rooms as $room) {
            $roomsMap[$room->id] = $room->room_name;
        }

        $balances = ZzyyUserBalance::with(['reserve', 'paytransaction'])->where('fa_zzyy_user_balance.user_id', $userId)->order('id', 'desc')->select();
        $recharge = [];
        $consume = [];
        foreach ($balances as $balance) {
            if (1 == $balance->type or 2 == $balance->type) {
                $recharge[] = [
                    'charge_type' => $balance->type,
                    'fee' => $balance->value,
                    'time' => date('Y/m/d H:i:s', $balance->createtime),
                    'order_num' => 2 == $balance->type ? '-' : $balance->paytransaction->out_trade_no,
                ];
            } else if (-1 == $balance->type) {
                if (null == $balance->reserve or ZzyyReserve::STATUS_CANCELLED == $balance->reserve->status) {  // 已经取消
                    continue;
                }
                $consume[] = [
                    'fee' => $balance->value,
                    'store' => $storesMap[$balance->reserve->store_id],
                    'room' => $roomsMap[$balance->reserve->room_id],
                    'reserve_time' => Ykxbon::parse($balance->reserve->starttime)->format('Y/m/d H:i') .' - '.
                        Ykxbon::parse($balance->reserve->endtime)->format('H:i'),
                    'order_time' => date('Y/m/d H:i:s', $balance->createtime),
                    'order_num' => $balance->reserve->trade_no ? $balance->reserve->trade_no : '-',
                ];
            }
        }

        $this->success('ok', [
            'balance' => $money,
            'charge_list' => $recharge,
            'consume_list' => $consume
        ]);
    }

}
